package com.zyy.clothesApplication.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

@Slf4j
public class AesEncryptUtils {
    private static final String KEY="9g3rhgv3nbrhu98g";

    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR="AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content,String encryptKey) throws Exception {
        //Cipher为加密和解密提供密码功能
        //转换：算法/模式/填充
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        //DECRYPT_MODE字段：用于将Cipher初始化为加密模式的常量
        cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(encryptKey.getBytes(),"AES"));
        //数据将被加密
        byte[] bytes = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr,String decryptKey)throws  Exception{
        //Cipher为加密和解密提供密码功能
        //转换：算法/模式/填充
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        //DECRYPT_MODE字段：用于将Cipher初始化为加密模式的常量
        cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(decryptKey.getBytes(),"AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        //对数据进行解密
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    /**
    *加密
    * */
    public static String encrypt(String content){
        try {
            return encrypt(content, KEY);
        } catch (Exception e) {
            log.error("对content加密失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密
     */
    public static String decrypt(String encryptStr){
        try {
            return decrypt(encryptStr, KEY);
        } catch (Exception e) {
            log.error("对encryptStr解密失败=>>{}",encryptStr);
            throw new RuntimeException(e);
        }
    }

}
